package com.hiwan.system.service.org;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hiwan.platform.utils.StringUtils;
import com.hiwan.system.cache.OrgCacheService;
import com.hiwan.system.dao.dept.DeptDao;
import com.hiwan.system.dao.org.OrgDao;
import com.hiwan.system.dao.user.UserDao;
import com.hiwan.system.pojo.DeptInfo;
import com.hiwan.system.pojo.OrgCacheInfo;
import com.hiwan.system.pojo.OrgInfo;
import com.hiwan.system.pojo.TreeNode;
import com.hiwan.system.pojo.UserCacheInfo;
import com.hiwan.system.pojo.UserInfo;
import com.hiwan.system.pojo.UserRelation;
import com.hiwan.system.service.dept.DeptService;
import com.hiwan.system.service.user.UserService;
import com.hiwan.system.util.CacheUtils;

@Service
@Transactional
public class OrgService implements OrgCacheService{

	@Autowired
	private UserService userService;
	@Autowired
	private DeptService deptService; 
	@Autowired
	private OrgDao orgDao;
	@Autowired
	private DeptDao deptDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	
	public boolean hasDept() {
		return deptService.hasDept();
	}

	public void sysInit() {
		List<OrgInfo> nodes = orgDao.getOrgListInit();
		for (OrgInfo o : nodes) {
			o.setRemark1("false");
			o.setRemark2(String.valueOf(hasDept()));
			OrgCacheInfo orgCacheInfo = OrgCacheInfo.cast2OrgCache(o,
					orgDao.getOrgListWithTree(o),
					deptDao.selectDeptList(o.getOrgId(), "", "deptB"),
					orgDao.getOrgList4Report(o.getOrgId()),
					deptDao.selectDeptList(o.getOrgId(), "", "orgC"));
			CacheUtils.put("sysCache", o.getOrgId(), orgCacheInfo);
			//cacheService.put("sysCache", o.getOrgId(), orgCacheInfo);
		}
	}

	/**
	 * 获得 缓存机构信息
	 * 
	 * @param orgId
	 * @return
	 */
	public OrgCacheInfo getOrgInfo(String orgId) {
		
		OrgCacheInfo orgCacheInfo = null;
				//(OrgCacheInfo)CacheUtils.get("sysCache", orgId);
		if(orgCacheInfo == null) {
			try {
				OrgInfo orgInfo = null;
				if (StringUtils.equals(orgId, "*")) {
					orgCacheInfo = new OrgCacheInfo();
					orgCacheInfo.setOrgId("*");
					orgCacheInfo.setOrgName("所有机构");
					orgCacheInfo.setStatus("1");
				} /*else if (orgId.endsWith("V") || orgId.endsWith("J")) {
					// 将虚拟出来的市区机构也缓存起来
					orgInfo = orgDao.selectVirtualOrgInfo(orgId);
					orgCacheInfo = OrgCacheInfo.cast2OrgCache(orgInfo, null,
							null, orgDao.getOrgList4Report(orgId),
							deptDao.selectDeptList(orgId, "", "orgC"));
				} */else {
					orgInfo = orgDao.selectOrgInfo(orgId);
					if (orgInfo != null) {
						orgInfo.setRemark1("false");
						// orgInfo.setRemark2(String.valueOf(hasDept()));
						orgCacheInfo = OrgCacheInfo.cast2OrgCache(orgInfo,
								orgDao.getOrgListWithTree(orgInfo),
								deptDao.selectDeptList(orgId, "", "orgA"),
								orgDao.getOrgList4Report(orgId),
								deptDao.selectDeptList(orgId, "", "orgC"));
					}

				}

				if (orgCacheInfo != null) {
					CacheUtils.put("sysCache", orgId, orgCacheInfo);
				}

			} catch (Exception ex) {
				ex.printStackTrace();
				return null;

			}
		}
		return orgCacheInfo;
	}
	//获取orgInfo的详细信息
	public OrgInfo getOnlyOrgInfo(String orgId){
		OrgInfo orgInfo = orgDao.selectOrgInfo(orgId);
		return orgInfo;
	}
	public OrgInfo selectOneByOrgCode(String orgCode) {
		return orgDao.selectOneByOrgCode(orgCode);
	}
	public OrgInfo selectOrgByAreaCode(String areaCode) {
		return orgDao.selectOrgByAreaCode(areaCode);
	}
	/**
	 * 获得机构名称
	 */
	public String getOrgName(String orgId) {
		if(StringUtils.isBlank(orgId))
			return "";
		OrgCacheInfo orgCacheInfo = getOrgInfo(orgId);
		if (orgCacheInfo != null) {
			return orgCacheInfo.getOrgName();
		} else {
			return "";
		}
	}

	public OrgInfo getRootOrgInfo() {
		return orgDao.selectRootOrgInfo();
	}

	/**
	 * 根据机构信息取得操作机构ID，用于虚拟机构下的用户提升操作权限 当机构为虚拟机构时，取父机构，当机构为实体机构时，取当前机构
	 * 例：省行（330000888）用户皆挂在实体机构浙江省分行本级（330000901）下，330000901在机构树上是挂在330000888下，当
	 * 省行用户（330000901）需要操作机构树时，需要有330000888的权限
	 * 
	 * @return
	 */
	public String getOperateOrgId(String orgId) {
		// OrgCacheInfo orgCacheInfo = getOrgInfo(orgId);
		// if (!StringUtils.isEmpty(orgCacheInfo.getVirtualOrg())) {
		// return orgCacheInfo.getVirtualOrg();
		// }
		return orgId;
	}

	/**
	 * 取得虚拟机构下得实体机构对应信息,如果无则返回机构ID本身
	 * 
	 * @param orgId
	 * @return
	 */
	public String getEntityOrgId(String orgId) {
		// if (StringUtils.endsWith(orgId, virtualOrgEnd)) {
		// return orgId.substring(0, orgId.length() - 3) + EntityOrgEnd;
		// }
		return orgId;
	}

	public String haveChildNodes(String messageId) throws NoSuchFieldException {
		return haveChildNodes("org", messageId);
	}

	public String haveChildNodes(String messageType, String messageId)
			throws NoSuchFieldException {
		return haveChildNodes(messageType, messageId, "org");
	}

	public String haveChildNodes(String messageType, String messageId,
			String checkType) throws NoSuchFieldException {
		return haveChildNodes(messageType, messageId, checkType, "notRoot",
				null);
	}

	
	/**
	 * 机构树获取下级节点
	 * id,pId,name,type,isParent,open,status,orgType,levelOrder
	 * @param messageType
	 *            查询参数类型，代表messageId的类型（org-机构，dept-部门，user-人员）
	 * @param messageId
	 *            查询参数数值
	 * @param checkType
	 *            查询结果类型，查询结果需要展示哪些数据(org-机构，dept-机构/部门，user-机构/部门/人员)
	 * @param isRoot
	 *            是否是取根节点，如果是则赋值“isRoot”
	 * @param noSuper
	 *            是否需要提升权限至上一级，默认情况下取根节点时，如果为实体机构，则提升一级权限，
	 *            有时特殊情况不需要提升权限，则设置此值为“noSuper”
	 * @return 单一字符串拼接顺序如下：id|pId|name|type|hasChild|open|status;
	 * @throws NoSuchFieldException
	 *             补充说明：目前查询中，没有出现部门为根节点，或者根据人员查询子节点的情况。此种情况的代码未编写，
	 *             待将来出现此种情况时再行补充。
	 */
	public String haveChildNodes(String messageType, String messageId,
			String checkType, String isRoot, String noSuper)
			throws NoSuchFieldException {
		// message参数定义
		// id 机构/部门/人员 的节点ID
		// pId 在机构树展示时，对应的上级ID
		// name 展示名称
		// type 节点属性 （org/dept/user）
		// hasChild 是否含有子节点（0-没有；1-有）
		// open 是否展开 （1-展开 2-折叠）
		// status 机构状态 0-未启用 1-启用 2-停用
		// Type 类型 1-机构 0-部门
		String message = "";
		// 控制参数，用来表示是否需要展示部门列表
		boolean isDept = StringUtils.equals(checkType, "dept");
		// 控制参数，用来表示是否需要展示用户列表
		boolean isUser = StringUtils.equals(checkType, "user");
		// 查询节点为机构
		if (StringUtils.isEmpty(messageType)
				|| StringUtils.equals(messageType, "org")) {
			// 查询时如果为根节点，则提升操作员的操作权限至虚拟机构
			OrgCacheInfo orgCacheInfo = StringUtils.equals(noSuper, "noSuper") ? getOrgInfo(messageId)
					: (StringUtils.equals(isRoot, "isRoot") ? getOrgInfo(getOperateOrgId(messageId))
							: getOrgInfo(messageId));
			List<String> orgInfoList = orgCacheInfo.getChildOrgList();
			if (orgInfoList != null) {
				for (String id : orgInfoList) {
					OrgCacheInfo o = this.getOrgInfo(id);
					String hasChild = "0";
					if ((isDept || isUser)
							&& (StringUtils.equals(o.getHasDept(), "1") || StringUtils
									.equals(o.getHasUser(), "1"))) {
						hasChild = "1";
					} else {
						hasChild = o.getHasChild();
					}
					message += o.getOrgId() + "|" + o.getParentId() + "|"
							+ o.getOrgName() + "|org|" + hasChild + "|2|"
							+ o.getStatus() + "|1|" + o.getLevelOrder() + ";";
				}
			}
			if (isDept || isUser) {
				if (hasDept()) {
					List<String> deptInfoList = orgCacheInfo.getChildDeptList();
					if (deptInfoList != null) {
						for (String deptId : deptInfoList) {
							DeptInfo d = deptService.getDeptInfo(deptId);
							// 判断是否有子节点
							int hasChild = d.getSubDeptOrg()
									+ (isUser ? d.getSubDeptUser() : 0);
							message += d.getDeptId()
									+ "|"
									+ (StringUtils.isEmpty(d.getParentDept()) ? d
											.getBelongOrg() : d.getParentDept())
									+ "|" + d.getDeptName() + "|dept|"
									+ (hasChild == 0 ? "0" : "1") + "|2|"
									+ d.getDeptStatus() + "|0;";
						}
					}
				} else {
					List<UserRelation> userInfoList = userDao
							.selectUserListByDept(orgCacheInfo.getOrgId(), null);
					if (userInfoList != null) {
						for (UserRelation u : userInfoList) {
							UserCacheInfo uc = userService.getUserCacheInfo(u
									.getUserId());
							if (uc != null) {
								message += u.getRelationId() + "|"
										+ u.getOrgId() + "|" + uc.getUserName()
										+ "|user|0|2|" + u.getStatus() + "|0;";
							}
						}
					}
				}
			}
			// 如果为根节点，添加根节点信息
			if (StringUtils.equals(isRoot, "isRoot")) {
				message = orgCacheInfo.getOrgId() + "|0|"
						+ orgCacheInfo.getOrgName() + "|org|1|1|1|1|"
						+ orgCacheInfo.getLevelOrder() + ";" + message;
			}
			// 查询节点为部门
		} else if (messageType.equals("dept")) {
			List<DeptInfo> deptInfoList = deptDao.selectDeptList("", messageId,
					"orgB");
			if (deptInfoList != null) {
				for (DeptInfo d : deptInfoList) {
					// 判断是否有子节点
					int hasChild = d.getSubDeptOrg()
							+ (isUser ? d.getSubDeptUser() : 0);
					message += d.getDeptId() + "|" + d.getParentDept() + "|"
							+ d.getDeptName() + "|dept|"
							+ (hasChild == 0 ? "0" : "1") + "|2|"
							+ d.getDeptStatus() + "|0;";
				}
			}
			if (isUser) {
				List<UserRelation> userInfoList = userDao.selectUserListByDept(
						null, messageId);
				if (userInfoList != null) {
					for (UserRelation u : userInfoList) {
						UserCacheInfo uc = userService.getUserCacheInfo(u
								.getUserId());
						message += u.getRelationId() + "|" + u.getDeptId()
								+ "|" + uc.getUserName() + "|user|0|2|"
								+ u.getStatus() + "|0;";
					}
				}
			}
			// TODO 暂未此情况的查询，待补充
			// 如果为根节点，添加根节点信息
			if (StringUtils.equals(isRoot, "isRoot")) {
				// message = orgCacheInfo.getOrgId() + "|0|" +
				// orgCacheInfo.getOrgName() + "|dept|0" + "|1;" + message;
			}
			// TODO 暂未此情况的查询，待补充
		} else if (messageType.equals("user")) {
			// List<DeptInfo> nodes = userDao.selectUserList("",messageId);
		}
		return message;
	}

	/**
	 * 根据mapid和parameter调用orgDao查询机构列表，并返回树形结构
	 * 
	 * @param mapId
	 *            由调用方提供，由namespace和sqlid组成,
	 *            形如com.hiwan.system.mapper.org.selectOrgInfo
	 *            mapid指向的sql必须可以与OrgInfo建立映射关系，否则会出现异常
	 * @param parameter
	 *            传给mybatis的参数，用法同mybatis的参数，可以是map、javabean
	 * @return
	 */
	public String getOrgTreeForCustomize(String mapId, Object parameter) {
		String message = "";
		List<OrgInfo> list = this.orgDao.getOrgTreeForCustomize(mapId,
				parameter);
		if (list != null) {
			for (OrgInfo o : list) {
				String isOpen = StringUtils.isEmpty(o.getLevelOrder()) ? "2"
						: o.getLevelOrder();
				String orgType = StringUtils.isEmpty(o.getOrgType()) ? "org"
						: o.getOrgType();
				message += o.getOrgId() + "|" + o.getParentId() + "|"
						+ o.getOrgName() + "|" + orgType + "|"
						+ o.getHasChild() + "|" + isOpen + "|" + o.getStatus()
						+ "|1;";
			}
		}
		return message;
	}

	/**
	 * 查询报表统计用机构数
	 * 
	 * @param orgId
	 * @param checkType
	 * @param isRoot
	 * @return
	 */
	public String getOrgTreeForReport(String orgId, String checkType,
			boolean isRoot) {
		String message = "";
		// 如果不是市机构本级机关，则获得子机构
		OrgCacheInfo subTreeRoot = getOrgInfo(orgId);
		List<String> list = subTreeRoot.getChildOrgList4Report();
		for (String id : list) {
			OrgCacheInfo info = getOrgInfo(id);
			String isOen = "2";

			// 判断是否有子节点 首先判断是否有子机构，如果没有子机构且需要展示部门，则判断是否有子部门
			String hasChild = info.getHasChild();
			if ((hasChild == null || hasChild.endsWith("0"))
					&& checkType.equals("dept")) {
				List<String> depts = info.getChildDeptList4Report();
				if (depts != null && depts.size() > 0) {
					hasChild = "1";
				} else {
					hasChild = "0";
				}

			}
			message += info.getOrgId() + "|" + info.getToOrgId() + "|"
					+ info.getOrgName() + "|org|" + hasChild + "|" + isOen
					+ "|" + info.getStatus() + "|1;";

		}
		if (isRoot) {
			message = subTreeRoot.getOrgId() + "|1|" + subTreeRoot.getOrgName()
					+ "|org|1|1|1|1;" + message;
		}
		// 加入部门信息
		if (checkType.equals("dept")) {

			List<String> depts = getOrgInfo(orgId).getChildDeptList4Report();
			for (String deptId : depts) {
				DeptInfo dept = deptService.getDeptInfo(deptId);
				message += dept.getDeptId()
						+ "|"
						+ (StringUtils.isEmpty(dept.getParentDept()) ? orgId
								: dept.getParentDept()) + "|"
						+ dept.getDeptName() + "|dept|"
						+ (dept.getSubDeptOrg() == 0 ? "0" : "1") + "|2|"
						+ dept.getDeptStatus() + "|0;";
			}
		}

		return message;
	}

	/**
	 * 刷新orgInfo所有父节点的缓存
	 * 
	 * @param orgInfo
	 */
	public void freshAllParentOrg(OrgInfo orgInfo) {
		String parentId = orgInfo.getParentId();
		while (StringUtils.isNotEmpty(parentId)) {
			removeOrgInfo(parentId);
			parentId = getOrgInfo(parentId)==null?"":getOrgInfo(parentId).getParentId();
		}
	}

	public String haveParentNodes(String messageId) {
		return haveParentNodes(messageId, "dept");
	}

	public String haveParentNodes(String messageId, String checkType) {
		return haveParentNodes("", messageId, checkType, true);
	}

	/**
	 * 机构树获取上级节点
	 * 
	 * @param messageType
	 *            查询参数类型，代表messageId的类型（org-机构，dept-部门，user-人员）
	 * @param messageId
	 *            查询参数数值
	 * @param checkType
	 *            查询结果类型，查询结果需要展示哪些数据(org-机构，dept-机构/部门，user-机构/部门/人员)
	 * @param orgType
	 *            该字段已作废 是否展示实体机构信息 true-展示 false-不展示（某些机构树选择时，需展示同级机构的实体机构及部门）
	 * @return
	 * id,pId,name,type,isParent,open,status,orgType,levelOrder
	 */
	public String haveParentNodes(String messageType, String messageId,
			String checkType, boolean orgType) {
		// message参数定义
		// id 机构/部门/人员 的节点ID
		// pId 在机构树展示时，对应的上级ID
		// name 展示名称
		// type 节点属性 （org/dept/user）
		// hasChild 是否含有子节点（0-没有；1-有）
		// open 是否展开 （1-展开 2-折叠）
		// status 机构状态 0-未启用 1-启用 2-停用
		String message = "";
		List<OrgCacheInfo> tempoList = new ArrayList<OrgCacheInfo>();
		// 控制参数，用来表示是否需要展示部门列表
		boolean isDept = StringUtils.equals(checkType, "dept");
		// 查询节点为机构
		if (StringUtils.isEmpty(messageType)
				|| StringUtils.equals(messageType, "org")) {
			String parentId = getOrgInfo(getOperateOrgId(messageId))
					.getParentId();
			String hasChild = "0";
			while (StringUtils.isNotEmpty(parentId)
					&& !StringUtils.equals(parentId, "0")) {
				OrgCacheInfo o = getOrgInfo(parentId);
				parentId = o.getParentId();
				if (StringUtils.isEmpty(parentId)) {
					o.setParentId("0");
				}
				if (isDept) {
					List<String> deptInfoList = o.getChildDeptList();
					if (deptInfoList.size() > 0) {
						hasChild = "1";
					}
					for (String deptId : deptInfoList) {
						DeptInfo d = deptService.getDeptInfo(deptId);
						for (DeptInfo tempD : deptDao.selectChildDeptList(d
								.getDeptId())) {
							message += tempD.getDeptId() + "|"
									+ tempD.getBelongOrg() + "|"
									+ tempD.getDeptName() + "|dept|0|2|"
									+ d.getDeptStatus() + ";";
						}
					}
				}
				tempoList.add(o);
				message = o.getOrgId() + "|" + o.getParentId() + "|"
						+ o.getOrgName() + "|org|" + hasChild + "|1|1;"
						+ message;
				hasChild = "1";
			}

			// 查询节点为部门
		} else if (messageType.equals("dept")) {
			// List<DeptInfo> nodes =
			// deptDao.selectDeptList("",messageId,"orgB");
			// for(DeptInfo d : nodes){
			// message += d.getDeptId() + "|" + d.getParentDept() + "|" +
			// d.getDeptName() + "|dept|" + (d.getSubDeptOrg() == 0? "0" : "1" )
			// + ";";
			// }
		} else if (messageType.equals("user")) {

		}

		return message;
	}

	/**
	 * 获取单个机构信息
	 * 
	 * @param id
	 * @return
	 */
	public OrgInfo haveOrgTreeInfo(String orgId) {
		return orgDao.selectOrgInfo(orgId);
	}

	public OrgInfo haveOrgInsert(String orgId) {
		OrgInfo o = new OrgInfo();
		o.setParentId(orgId);
		o.setHasChild("0");
		// o.setOrgLevel(String.valueOf(Integer.valueOf(getOrgInfo(orgId)
		// .getOrgLevel()) + 1));
		o.setTreeLevel(String.valueOf(Integer.valueOf(getOrgInfo(orgId)
				.getTreeLevel()) + 1));
		o.setToOrgId(orgId);
		return o;
	}

	/**
	 * 新增或修改机构信息
	 * 
	 * @param orgInfo
	 * @param operFlag
	 *            1-新增 2-修改
	 * @param userId
	 *            操作用户
	 * @return
	 * @throws NoSuchFieldException
	 */
	public String saveOrgInfo(OrgInfo orgInfo, String operFlag, String userId)
			throws NoSuchFieldException {

		String message = "";
		
		String productStrs=orgInfo.getProductId();
		String [] productIdArray = null;
		String [] teleArray = null;
		if(StringUtils.isNotBlank(productStrs)){
			productIdArray=productStrs.substring(1).split(",");
			teleArray = orgInfo.getCustManagerMobile().substring(1).split(",");
		}
		
		// 新增
		if (StringUtils.equals(operFlag, "1")) {
			if (getOrgInfo(orgInfo.getOrgId()) != null) {
				return "机构已存在";
			}
			orgInfo.setCreateUser(userId);
			// 检查to_org_id是否存在环的问题
			if (checkHasCycle(orgInfo)) {
				return "您指定的统计归属机构会导致统计归属机构出现循环，请重新指定";
			}
			orgDao.insertOrgInfo(orgInfo);
			
			message ="{\"success\":\"新增机构成功!\"}";
			// 修改
		} else {
			if (StringUtils.isEmpty(orgInfo.getParentId())) {
				orgInfo.setTreeLevel("1");
			} else {
				OrgCacheInfo parentOrg = getOrgInfo(orgInfo.getParentId());
				orgInfo.setUpdateUser(userId);
				orgInfo.setTreeLevel(String.valueOf(Integer.parseInt(parentOrg
						.getTreeLevel()) + 1));
			}

			// 检查to_org_id是否存在环的问题
			if (checkHasCycle(orgInfo)) {
				return "您指定的统计归属机构会导致统计归属机构出现循环，请重新指定";
			}
			orgDao.updateOrgInfo(orgInfo);
			orgDao.updateOrgHasChild(orgInfo.getParentId());
			
			// 删除缓存信息（上级机构，以后使用时，会自动加载该机构至缓存）
			removeOrgInfo(orgInfo.getOrgId());
			message = "{\"success\":\"机构修改成功!\"}";

		}
		// 新增父机构的本级虚拟机构
		/*if (!StringUtils.isEmpty(orgInfo.getParentId())) {
			addVirtualOrgForParent(orgInfo);
		}*/
		
		// 删除缓存信息
		freshAllParentOrg(orgInfo);
		return message;
	}

	/**
	 * 新增子机构时，为父机构自动添加本级机构
	 * 
	 * @param orgInfo
	 * @return
	 */
	public boolean addVirtualOrgForParent(OrgInfo orgInfo) {
		// 判断是否已经存在该虚拟机构 若不存在则新增
		if (this.getOrgInfo(orgInfo.getParentId() + "V") == null) {
			OrgInfo virtualOrg = new OrgInfo();
			OrgCacheInfo entryOrg = this.getOrgInfo(orgInfo.getParentId());
			virtualOrg.setOrgId(entryOrg.getOrgId() + "V");
			virtualOrg.setOrgName(entryOrg.getOrgName() + "本级");
			virtualOrg.setOrgLevel(entryOrg.getOrgLevel());
			virtualOrg.setTreeLevel(String.valueOf(Integer.parseInt(entryOrg
					.getTreeLevel()) + 1));
			virtualOrg.setStatus("1");
			virtualOrg.setToOrgId(orgInfo.getOrgId());
			if (orgDao.insert("com.hiwan.system.mapper.org",
					"insertVirtualOrg", virtualOrg) > 0) {
				return true;
			} else {
				return false;
			}
		}
		return true;
	}

	/*
	 * 检查是否存在环
	 */
	private boolean checkHasCycle(OrgInfo orgInfo) {
		String toOrgId = orgInfo.getToOrgId();
		while (!StringUtils.isEmpty(toOrgId)) {
			toOrgId = getOrgInfo(toOrgId).getToOrgId();
			if (orgInfo.getOrgId().equals(toOrgId)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 删除机构信息
	 * @param orgInfo 
	 * @param userId
	 *            操作用户
	 * @return
	 */
	public String deleteOrgInfo(OrgInfo orgInfo, String userId) {
		OrgInfo tempO = orgDao.selectOrgInfo(orgInfo.getOrgId());
		if (!StringUtils.equals(tempO.getStatus(), "2")) {
			return "该机构未停用，不能删除！";
		}
		if(!StringUtils.equals(tempO.getHasChild(), "0")){
			return "该机构下面有子机构，不能删除！";
		}
		if(!queryDept(tempO.getOrgId())){
			return "该机构下面有子部门，不能删除！";
		}
		UserInfo user = new UserInfo();
		user.setOrgId(orgInfo.getOrgId());
		List<UserInfo> lUser = userDao.selectListPage(user);
		if(lUser != null && lUser.size() > 0){
			return "该机构下面还有人员，不能删除！";
		}
		List<OrgCacheInfo> orgInfoList = haveChildList(
				new ArrayList<OrgCacheInfo>(), orgInfo.getOrgId());
		for (OrgCacheInfo o : orgInfoList) {
			CacheUtils.remove("sysCache", o.getOrgId());
		}
		// 删除缓存信息
		removeOrgInfo(tempO.getParentId());
		// TODO 添加操作日志，同新增、修改
		orgDao.deleteOrgInfo(tempO);
		return "{\"success\":\"机构删除成功!\"}";
	}
	
	public boolean queryDept(String orgId){
		List<DeptInfo> deptList = deptService.getDeptList(orgId, null, "orgC");
		if(deptList.size()>0){
			return false;
		}else{
			return true;
		}
		
	}
	
	
	/**
	 * 取得下级机构列表
	 * 
	 * @param orgInfoList
	 * @param orgId
	 * @return
	 */
	public List<OrgCacheInfo> haveChildList(List<OrgCacheInfo> orgInfoList,
			String orgId) {
		if (orgInfoList == null) {
			orgInfoList = new ArrayList<OrgCacheInfo>();
		}
		OrgCacheInfo oci = getOrgInfo(orgId);
		if (oci != null) {
			orgInfoList.add(oci);
			if (oci.getChildOrgList() != null) {
				for (String id : oci.getChildOrgList()) {
					haveChildList(orgInfoList, id);
				}
			}
		}
		return orgInfoList;
	}

	/**
	 * 仅获取orgId的子树
	 * 
	 * @param orgId
	 * @param isContainSelf
	 *            是否包含orgId自身
	 * @return
	 */
	public List<OrgInfo> getOnlyChildOrgList(String orgId, boolean isContainSelf) {

		return orgDao.selectOnlyChildOrgList(orgId, isContainSelf);
	}

	/**
	 * 删除机构缓存信息 在机构、部门、用户修改时，需要更新机构树上是否展示子节点信息，故需删除对应机构的机构信息，以后加载时，会自动加载
	 * 机构信息需删除三级，部门两级，用户一级
	 * 
	 * @param orgId
	 */
	public void removeOrgInfo(String orgId) {
		removeOrgInfo(orgId, 2);
	}

	public void removeOrgInfo(String orgId, int rmLevel) {
		int num = 0;
		String tempId = orgId;
		while (num < rmLevel) {
			OrgCacheInfo o = getOrgInfo(tempId);
			if (o != null) {
				CacheUtils.remove("sysCache", tempId);
				if (StringUtils.isNotEmpty(o.getParentId())) {
					tempId = o.getParentId();
				}
			} else {
				return;
			}
			num++;
		}
	}

	/**
	 * 检查upOrg是否blowOrg的直属上级
	 * 
	 * @param blowOrg
	 *            下级机构
	 * @param upOrg
	 *            上级机构
	 * @return
	 */
	public boolean isBelowOrg(String blowOrg, String upOrg) {
		if (upOrg == null || blowOrg == null) {
			return false;
		}

		OrgCacheInfo upInfo = getOrgInfo(upOrg);
		if (upInfo == null) {
			return false;
		}

		OrgCacheInfo belowInfo = getOrgInfo(blowOrg);
		if (belowInfo == null) {
			return false;
		}

		// if (!StringUtils.isEmpty(belowInfo.getVirtualOrg())) {
		// blowOrg = belowInfo.getVirtualOrg();
		// belowInfo = getOrgInfo(blowOrg);
		// }

		// if (!StringUtils.isEmpty(upInfo.getVirtualOrg())) {
		// upOrg = upInfo.getVirtualOrg();
		// }

		if (blowOrg.equals(upOrg)) {
			return false;
		}

		while (belowInfo != null) {
			if (upOrg.equals(belowInfo.getParentId())) {
				return true;
			}

			belowInfo = getOrgInfo(belowInfo.getParentId());
		}

		return false;
	}

	/**
	 * 根据newOrgId查询oldOrgId,如果oldOrgId多于一个则抛出异常
	 * 
	 * @param newOrgId
	 * @return
	 */
	public String getOldOrgIdByNewOrgId(String newOrgId) throws Exception {
		List<String> list = this.orgDao.getOldOrgIdListByNewOrgId(newOrgId);
		if (list == null || list.size() == 0) {
			return null;
		}
		if (list.size() > 1) {
			throw new Exception(
					"新机构代码对应多个旧机构代码，请使用 List<String> getOldOrgIdListByNewOrgId(String newOrgId) 接口");
		}
		return list.get(0);
	}

	/**
	 * 根据newOrgId查询oldOrgId列表
	 * 
	 * @param newOrgId
	 * @return
	 */
	public List<String> getOldOrgIdListByNewOrgId(String newOrgId) {

		return this.orgDao.getOldOrgIdListByNewOrgId(newOrgId);
	}

	/**
	 * 根据olbOrgId查询newOrgId
	 * 
	 * @param oldOrgId
	 * @return
	 */
	public String getNewOrgIdByOldOrgId(String oldOrgId) {
		return orgDao.getNewOrgIdByOldOrgId(oldOrgId);
	}

	/**
	 * demoOldOrgidPlugin使用demo
	 * 
	 * @param newOrgId
	 * @return
	 */
	public List<OrgInfo> demoOldOrgPlugin(String newOrgId) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("newOrgId", newOrgId);
		// 参数map可以使用Map、javaBean，如果只有一个参数还可以使用String，看"com.hiwan.system.mapper.org.demoNewOrgidPlugin"如何定义
		// 如果使用map或javaBean 则必须有newOrgId字段
		return this.orgDao.selectList("com.hiwan.system.mapper.org",
				"demoOldOrgidPlugin", newOrgId, OrgInfo.class);
	}

	/**
	 * demoNewOrgidPlugin使用demo
	 * 
	 * @param newOrgId
	 * @return
	 */
	public List<OrgInfo> demoNewOrgPlugin(String OldOrgId) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("OldOrgId", OldOrgId);
		// 参数map可以使用Map、javaBean，如果只有一个参数还可以使用String，看"com.hiwan.system.mapper.org.demoNewOrgidPlugin"如何定义
		// 如果使用map或javaBean 则必须有OldOrgId字段
		return this.orgDao.selectList("com.hiwan.system.mapper.org",
				"demoNewOrgidPlugin", map, OrgInfo.class);
	}

	/**
	 * 修改OrgInfo的levelOrder为newLevelOrder，同时调整其他受影响的机构的levelOrder(同时递增或递减)
	 * 
	 * @param orgInfo
	 */
	public void modifyOrgLevelOrder(OrgInfo orgInfo) {
		int oldLevelOrder = Integer.parseInt(orgInfo.getLevelOrder());
		int newLevelOrder = Integer.parseInt(orgInfo.getNewLevelOrder());
		int maxLevelOrder = 0, minLevelOrder = 0, step;
		String parentId = orgInfo.getParentId();
		// 如果被移动机构新顺序比旧顺序大，受其影响的其他机构顺序递减，反之递增
		if (newLevelOrder > oldLevelOrder) {
			maxLevelOrder = newLevelOrder;
			minLevelOrder = oldLevelOrder + 1; // 自身记录除外
			step = -1;
		} else {
			maxLevelOrder = oldLevelOrder - 1; // 自身记录除外
			minLevelOrder = newLevelOrder;
			step = 1;
		}
		orgDao.updateOtherOrgLevelOrder(parentId, maxLevelOrder, minLevelOrder,
				step);
		orgDao.updateOrgLevelOrder(orgInfo);

		// 刷新缓存
		OrgCacheInfo parentOrg = getOrgInfo(parentId);
		if (parentOrg != null) {
			CacheUtils.remove("sysCache", parentId);
			for (String subOrgId : parentOrg.getChildOrgList()) {
				CacheUtils.remove("sysCache", subOrgId);
			}
		}

	}
	public List<TreeNode> haveChildNode(String messageType, String messageId,
			String checkType,String isCheckOrg) throws NoSuchFieldException {
		return haveChildNode(messageType, messageId, checkType, "notRoot",
				null,isCheckOrg);
	}
	/**
	 * 
	 * @param messageType
	 * @param messageId
	 * @param checkType
	 * @param isRoot
	 * @param noSuper
	 * @return
	 * @throws NoSuchFieldException
	 */
	public List<TreeNode> haveChildNode(String messageType, String messageId,
			String checkType, String isRoot, String noSuper, String isCheckOrg)throws NoSuchFieldException {
		 List<TreeNode> nodeList = new ArrayList<TreeNode>();
		boolean isDept = StringUtils.equals(checkType, "dept");
		
		TreeNode treeNode =null;
		// 查询节点为机构
		if (StringUtils.isEmpty(messageType)
					|| StringUtils.equals(messageType, "org")) {
					// 查询时如果为根节点，则提升操作员的操作权限至虚拟机构
					OrgCacheInfo orgCacheInfo =
							StringUtils.equals(noSuper, "noSuper") ? getOrgInfo(messageId)
							: (StringUtils.equals(isRoot, "isRoot") ? getOrgInfo(getOperateOrgId(messageId))
									: getOrgInfo(messageId));
					List<String> orgInfoList = orgCacheInfo.getChildOrgList();
					if (orgInfoList != null) {
						for (String id : orgInfoList) {
							OrgCacheInfo o = this.getOrgInfo(id);
							String hasChild = "0";
							if ((isDept)&& (StringUtils.equals(o.getHasDept(), "1")
									|| StringUtils.equals(o.getHasUser(), "1"))) {
								hasChild = "1";
							} else {
								hasChild = o.getHasChild();
							}
							if(StringUtils.equals(isCheckOrg, "0")){
								treeNode =TreeNode.buildTreeNode(o.getOrgId(),o.getParentId(),
										o.getOrgName() ,"org",hasChild,"2", o.getStatus(),"1",o.getLevelOrder(),"false","false");
							}else{
								treeNode =TreeNode.buildTreeNode(o.getOrgId(),o.getParentId(),
										o.getOrgName(),"org",hasChild,"2", o.getStatus(),"1",o.getLevelOrder(),"false","false");
							}
							nodeList.add(treeNode);
						}
					}
					if (isDept) {
						if (hasDept()) {
							List<String> deptInfoList = orgCacheInfo.getChildDeptList();
							if (deptInfoList != null) {
								for (String deptId : deptInfoList) {
									DeptInfo d = deptService.getDeptInfo(deptId);
									// 判断是否有子节点
									String hasChild = d.getSubDeptOrg()== 0 ? "0" : "1";
									if(StringUtils.equals(isCheckOrg, "0")){
										treeNode = TreeNode.buildTreeNode(d.getDeptId(),
												(StringUtils.isEmpty(d.getParentDept()) ? d.getBelongOrg() : d.getParentDept()),
												d.getDeptName(),"dept",hasChild ,"2",d.getDeptStatus(),"0","","false","false");	
									}else{
										treeNode = TreeNode.buildTreeNode(d.getDeptId(),
												(StringUtils.isEmpty(d.getParentDept()) ? d.getBelongOrg() : d.getParentDept()),
												d.getDeptName(),"dept",hasChild ,"2",d.getDeptStatus(),"0","","false","false");
									}
									nodeList.add(treeNode);
								}
							}
						} 
					}
					// 如果为根节点，添加根节点信息
					if (StringUtils.equals(isRoot, "isRoot")) {
						if(StringUtils.equals(isCheckOrg, "0")){
							treeNode = TreeNode.buildTreeNode(orgCacheInfo.getOrgId(),orgCacheInfo.getParentId(),
									orgCacheInfo.getOrgName(),"org","1","1", "1","1",orgCacheInfo.getLevelOrder(),"false","false");
						}else{
							treeNode = TreeNode.buildTreeNode(orgCacheInfo.getOrgId(),orgCacheInfo.getParentId(),
									orgCacheInfo.getOrgName(),"org","1","1", "1","1",orgCacheInfo.getLevelOrder(),"false","false");
						}
						nodeList.add(treeNode);
					}
					// 查询节点为部门
				} else if (messageType.equals("dept")) {
					List<DeptInfo> deptInfoList = deptDao.selectDeptList("", messageId,
							"orgB");
					if (deptInfoList != null) {
						for (DeptInfo d : deptInfoList) {
							// 判断是否有子节点
							String hasChild = d.getSubDeptOrg()== 0 ? "0" : "1";
							treeNode =TreeNode. buildTreeNode(d.getDeptId(),
									(StringUtils.isEmpty(d.getParentDept()) ? d.getBelongOrg() : d.getParentDept()),
									d.getDeptName(),"dept",hasChild,"2",d.getDeptStatus(),"0","","false","false");
							nodeList.add(treeNode);
						}
					}
				} 
		return nodeList;
	}
	
	public boolean getDeptByName(DeptInfo deptInfo){
		List<DeptInfo> deptList = deptService.getDeptByName(deptInfo.getDeptName(),deptInfo.getParentDept() , deptInfo.getBelongOrg());
		if(StringUtils.isBlank(deptInfo.getDeptId()) && deptList.size() >0 ){
			return true;
		}else
		if(deptInfo.getDeptId()!=null&& deptList.size()==1){//修改部门信息，size=1是没有同名的其他部门
			return false;
		}
		else{
			return false;
		}
	}
	
	public List<TreeNode> getDeptList(String orgId){
		List<TreeNode> deptNodes = new ArrayList<TreeNode>();
		TreeNode treeNode =null;
		OrgCacheInfo orgInfo =  getOrgInfo(orgId);
		if(orgInfo !=null ){
			String hasChild = "0";
			if ((StringUtils.equals(orgInfo.getHasDept(), "1")
					|| StringUtils.equals(orgInfo.getHasUser(), "1"))) {
				hasChild = "1";
			} else {
				hasChild = orgInfo.getHasChild();
			}
			 treeNode =TreeNode.buildTreeNode(orgInfo.getOrgId(),orgInfo.getParentId(),
					 orgInfo.getOrgName(),"org",hasChild,"1", orgInfo.getStatus(),"1",orgInfo.getLevelOrder(),"false","false");
			 deptNodes.add(treeNode);
		}
		List<DeptInfo> deptInfoList = deptService.getDeptList(orgId, null, "orgA");
		if (deptInfoList != null) {
			for (DeptInfo d : deptInfoList) {
				// 判断是否有子节点
				String hasChild = d.getSubDeptOrg()== 0 ? "0" : "1";
				treeNode =TreeNode. buildTreeNode(d.getDeptId(),
						(StringUtils.isEmpty(d.getParentDept()) ? d.getBelongOrg() : d.getParentDept()),
						d.getDeptName(),"dept",hasChild,"2",d.getDeptStatus(),"0","","false","false");
				deptNodes.add(treeNode);
			}
		}
		return deptNodes;
		
	}
	
	public List<OrgInfo> selectOrgList(OrgInfo orgInfo){
		return orgDao.selectOrgList(orgInfo);
	}
	
	public List<OrgInfo> selectOrgInfoByProductId(OrgInfo orgInfo){
		return orgDao.selectOrgInfoByProductId(orgInfo);
	}
	
	public int insertOrgInfoFromXXZ(OrgInfo orgInfo){
		return orgDao.insertOrgInfoFromXXZ(orgInfo);
	}
	public int updateOrgInfoFromXXZ(OrgInfo orgInfo){
		return orgDao.updateOrgInfoFromXXZ(orgInfo);
	}
	public int deleteOrg(OrgInfo orgInfo){
		return orgDao.deleteOrg(orgInfo);
	}
	/**
	 * 区域
	 * @param orgInfo
	 * @return
	 */
//	public List<OrgInfo> getOrgRegion(OrgInfo orgInfo){
//		return orgDao.getOrgRegion( orgInfo);
//	}
	/**
	 * 支行
	 * @param orgInfo
	 * @return
	 */
//	public List<OrgInfo> getOrgBranch(OrgInfo orgInfo){
//		return orgDao.getOrgBranch(orgInfo);
//	}
}
